package view;

import util.Controller;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class Car extends JLabel implements Runnable{
	
    private int x;
    private int y;
    private int r;
    private Controller controller;
	ImageIcon img = new ImageIcon("img\\car.png");
    
    public Car(int r, Controller controller) {
        this.x = -25;
        this.y = 100 * r + 110;
        this.r = r;
        this.controller = controller;
	}
    
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(img.getImage(), 0, 0,  null);
    }
    
    private boolean touchZombie(){
        List <Zombie> zombies = controller.getZombieLists().get(r);
        if (zombies.isEmpty())
            return false;
        for (Zombie zombie:zombies){
            int dis = Math.abs(x-40-zombie.getX());
            if (dis<5){
                zombie.die();
                return true;              
            }
        }
        return false;
    }
    
	@Override
	public void run() {
        controller.getLayeredPane().add(this, new Integer(119+r));
        this.setVisible(true);
    	this.setBounds(x, y,
                img.getIconWidth(), img.getIconHeight());
        while(!touchZombie()) {
        	try {
				Thread.sleep(3);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
        while (x<800){
            try {
            	touchZombie();
            	this.setBounds(x, y,
                        img.getIconWidth(), img.getIconHeight());
                Thread.sleep(3);
                x += 1;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.setVisible(false);
        controller.getCarList().get(r).remove(this);	
        }
}
